var express = require('express');
var router = express.Router();
const { Category, Course } = require('../../models');
const { Op } = require('sequelize');
const { successResponse, failureResponse } = require('../../utils/responses')
const { delKey } = require('../../utils/redis');

router.get('/', async function(req, res, next) {
  try {
    const { name } = req.query;
    // const currentPage = parseInt(req.query.currentPage) || 1; // 当前页码，默认为 1
    // const pageSize = parseInt(req.query.pageSize) || 10; // 每页数量，默认为 10
    // const offset = (currentPage - 1) * pageSize;
    const condition = {
      order: [['rank', 'ASC'], ['id', 'DESC']], // 按照 id 降序排列
      where: {}
    }
    if (name) {
      condition.where.name = {
        [Op.like]: `%${name}%` // 模糊查询标题
      }
    }
    // 查询所有分类
    const categories = await Category.findAll(condition)
    successResponse(res, '查询分类列表成功', { categories })
  } catch (error) {
    failureResponse(res, error)
  }
});

router.get('/:id', async function(req, res, next) {
  try {
    const { id } = req.params;
    const condition = {
      include: [{
        model: Course,
        as: 'courses'
      }]
    }
    // 查询主键 id 的分类
    const category = await Category.findByPk(id, condition);
    if (!category) {
      return res.status(404).json({
        status: false,
        message: 'Category not found',
      });
    }
    res.json({
      status: true,
      message: 'Category fetched successfully',
      data: {
        category
      }
    });
  } catch (error) {
    res.status(500).json({
      status: false,
      message: 'Failed to fetch category',
      error: [error.message]
    });
  }
})

router.post('/', async function(req, res, next) {
  try {
    const category = await Category.create(filterBody(req.body));
    await delKey('categories');
    res.status(201).json({
      status: true,
      message: 'Category created successfully',
      data: {
        category
      }
    });
  } catch (error) {
    if (error.name === 'SequelizeValidationError') {
      return res.status(400).json({
        status: false,
        message: '请求参数错误',
        error: error.errors.map(err => err.message)
      });
    } else {
      res.status(500).json({
        status: false,
        message: 'Failed to create category',
        error: [error.message]
      });
    }
  }
})

router.delete('/:id', async function(req, res, next) {
  const { id } = req.params;
  try {
    const category = await Category.findByPk(id);
    if (!category) {
      return res.status(404).json({
        status: false,
        message: 'Category not found',
      });
    }
    // 删除前查询是否有关联的子表课程数据
    const courseCount = await Course.count({ wherr: { categoryId: id } });
    if (courseCount > 0) {
      throw new Error('当前分类有课程, 无法删除');
    }
    await category.destroy();
    await delKey('categories');
    res.json({
      status: true,
      message: 'Category deleted successfully',
    });
  } catch (error) {
    res.status(500).json({
      status: false,
      message: 'Failed to delete category',
      error: [error.message]
    });
  }
})

router.put('/:id', async function(req, res, next) {
  const { id } = req.params;
  try {
    const category = await Category.findByPk(id);
    if (!category) {
      return res.status(404).json({
        status: false,
        message: 'Category not found',
      });
    }
    await category.update(filterBody(req.body));
    await delKey('categories');
    res.json({
      status: true,
      message: 'Category update successfully',
      data: {
        category
      }
    });
  } catch (error) {
    res.status(500).json({
      status: false,
      message: 'Failed to update category',
      error: [error.message]
    });
  }
})

// 白名单过滤(强参数过滤)，只添加需要的字段
function filterBody(body) {
  const { name, rank } = body;
  return {
    name: name ? name.trim() : '',
    rank: rank ? rank.trim() : ''
  };
}

module.exports = router;
